import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Form,
  Image,
  Input,
  Modal,
  Radio,
  Space,
  Table,
  Tabs,
  TabsProps,
  Upload,
  UploadProps,
  message,
} from 'antd';
import { useEffect, useState } from 'react';
import {
  getCommodity_order,
  getDrug_order,
  getMedical_service_order,
  getMy,
  getPost,
  postDelOrder,
  postDelmedical_service_order,
  postUpdateInfo,
  postUpdatePassword,
  deletePost,
  getView,
  delView
} from '../Register/service';

const { Search } = Input;

const Mine = (props) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [img, setImg] = useState(null);
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [avatar, setAvatar] = useState('');
  const [userDetail, setUserDetail] = useState({});
  const form = Form.useForm();
  const [commodityList, setCommodityList] = useState([]);
  const [medicalList, setMedicalList] = useState([]);
  const [refreshCount, setRefreshCount] = useState(0);
  const [drugList, setDrugList] = useState([]);
  const [postsList, setPostsList] = useState([]);
  const [viewList,setViewList] = useState([])

  const fetchMy = async () => {
    const result = await getMy({
      uid: JSON.parse(window.localStorage.getItem('token')),
    });
    if (result.state === 200) {
      console.log(result.data);
      // form.setFieldsValue({username:'dddd'})
      setUserDetail(result.data);
    }
  };
  const fetchCommodity_order = async () => {
    const result = await getCommodity_order({
      uid: window.localStorage.getItem('token'),
    });
    if (result.state === 200) {
      console.log(result.data);
      setCommodityList(result.data);
    }
  };
  const fetchMedical_service_order = async () => {
    const result = await getMedical_service_order({
      uid: window.localStorage.getItem('token'),
    });
    if (result.state === 200) {
      console.log(result.data);
      setMedicalList(result.data);
    }
  };
  const fetchDrug_order = async () => {
    const result = await getDrug_order({
      uid: window.localStorage.getItem('token'),
    });
    if (result.state === 200) {
      setDrugList(result.data);
    }
  };
  const fetchPosts = async () => {
    const result = await getPost({
      uid: window.localStorage.getItem('token'),
      pageNum: 1,
    });
    if (result.state === 200) {
      setPostsList(result.data);
    }
  };
  const fetchView = async () => {
    const result = await getView({
      uid: window.localStorage.getItem('token'),
      pageNum: 1,
    });
    if (result.state === 200) {
      setViewList(result.data);
    }
  };
  useEffect(() => {
    fetchMy();
    fetchCommodity_order();
    fetchMedical_service_order();
    fetchDrug_order();
    fetchPosts();
    fetchView();
  }, [refreshCount]);

  const onChange = (key: string) => {
    console.log(key);
  };


  const columns = [
    {
      title: '商品名',
      dataIndex: 'mtype',
      key: 'mtype',
    },
    {
      title: '预定数量',
      dataIndex: 'mnum',
      key: 'mnum',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <Space>
            <Button
              onClick={async () => {
                const result = await postDelmedical_service_order({
                  oid: row?.oid,
                });
                if (result.state === 200) {
                  message.success('完成订单');
                  setRefreshCount(refreshCount + 1);
                }
              }}
            >
              完成
            </Button>
            <Button
              onClick={async () => {
                const result = await postDelmedical_service_order({
                  oid: row?.oid,
                });
                if (result.state === 200) {
                  message.success('取消订单');
                  setRefreshCount(refreshCount + 1);
                }
              }}
            >
              取消
            </Button>
          </Space>
        );
      },
    },
  ];

  const columns2 = [
    // {
    //   title: '商品图片',
    //   dataIndex: 'name',
    //   key: 'name',
    // },
    {
      title: '商品名',
      dataIndex: 'drugType',
      key: 'drugType',
    },
    {
      title: '预定数量',
      dataIndex: 'drugNum',
      key: 'drugNum',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <Space>
            <Button
              onClick={async () => {
                const result = await postDelOrder({
                  oid: row?.oid,
                });
                if (result.state === 200) {
                  message.success('完成订单');
                  setRefreshCount(refreshCount + 1);
                }
              }}
            >
              完成
            </Button>
            <Button
              onClick={async () => {
                const result = await postDelOrder({
                  oid: row?.oid,
                });
                if (result.state === 200) {
                  message.success('取消订单');
                  setRefreshCount(refreshCount + 1);
                }
              }}
            >
              取消
            </Button>
          </Space>
        );
      },
    },
  ];

  const dataSource3 = [
    {
      key: '1',
      name: '11',
      age: 32,
      address: '2',
    },
    {
      key: '2',
      name: '胡彦祖',
      age: 42,
      address: '1',
    },
  ];

  const columns4 = [
    {
      title: '商品图片',
      dataIndex: 'picture',
      key: 'picture',
      render: (_, row) => {
        return (
          <img
            style={{ width: '50px', height: '50px' }}
            src={JSON.parse(row?.picture)}
            alt=""
          />
        );
      },
    },
    {
      title: '商品名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '预定数量',
      dataIndex: 'c_num',
      key: 'c_num',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <Space>
            <Button
              onClick={async () => {
                const result = await postDelOrder({
                  oid: row?.oid,
                });
                if (result.state === 200) {
                  message.success('完成订单');
                  setRefreshCount(refreshCount + 1);
                }
              }}
            >
              完成
            </Button>
            <Button
              onClick={async () => {
                const result = await postDelOrder({
                  oid: row?.oid,
                });
                if (result.state === 200) {
                  message.success('取消订单');
                  setRefreshCount(refreshCount + 1);
                }
              }}
            >
              取消
            </Button>
          </Space>
        );
      },
    },
  ];

  const dataSource4 = [
    {
      key: '1',
      name: '胡彦斌',
      age: '猫砂',
      address: 11,
    },
    {
      key: '2',
      name: '胡彦祖',
      age: '猫砂',
      address: 11,
    },
  ];

  const columns3 = [
    {
      title: '评论内容',
      dataIndex: 'view',
      key: 'view',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <Space>
            {/* <Button>修改</Button> */}
            <Button onClick={async () => {
              const reuslt = await delView({
                vid:row?.vid
              })
              if(reuslt.state === 200){
                message.success('删除成功')
                setRefreshCount(refreshCount + 1)
              }
            }}>删除</Button>
          </Space>
        );
      },
    },
  ];

  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.onload = () => {
      const Base64Data = reader.result;
      setAvatar(Base64Data);
    };
    reader.readAsDataURL(img);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      console.log(info);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const items2: TabsProps['items'] = [
    {
      key: '1',
      label: `用户医疗服务订单`,
      children: (
        <div>
          <Table dataSource={medicalList} columns={columns} />
        </div>
      ),
    },
    {
      key: '2',
      label: `用户医疗用品订单`,
      children: (
        <div>
          <Table dataSource={drugList} columns={columns2} />
        </div>
      ),
    },
    {
      key: '3',
      label: `用户商品订单`,
      children: (
        <div>
          <Table dataSource={commodityList} columns={columns4} />
        </div>
      ),
    },
  ];
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `用户信息`,
      children: (
        <div>
          {
            <Form
              name="basic"
              // form={form}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 12 }}
              style={{ maxWidth: 600 }}
              initialValues={{ remember: true }}
              onFinish={async (val) => {
                const result = await postUpdateInfo({
                  // avatar:JSON.stringify(img),
                  ...val,
                  avatar: avatar ? JSON.stringify(avatar) : null,
                  uid: JSON.parse(window.localStorage.getItem('token')),
                });
                if (result.state === 200) {
                  message.success('更新成功');
                }
                console.log(result);
              }}
              // onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              {userDetail.username && (
                <Form.Item
                  label="用户名"
                  name="username"
                  initialValue={userDetail?.username}
                >
                  <Input />
                </Form.Item>
              )}

              {userDetail.username && (
                <Form.Item
                  label="电话号码"
                  name="phone"
                  initialValue={userDetail?.phone}
                >
                  <Input />
                </Form.Item>
              )}

              {userDetail.username && (
                <Form.Item
                  label="邮箱"
                  name="email"
                  initialValue={userDetail?.email}
                >
                  <Input />
                </Form.Item>
              )}

              {userDetail.username && (
                <Form.Item
                  label="性别"
                  name="gender"
                  initialValue={userDetail?.gender}
                >
                  <Radio.Group>
                    <Radio value="1"> 男 </Radio>
                    <Radio value="0"> 女 </Radio>
                  </Radio.Group>
                </Form.Item>
              )}
              {userDetail?.username && (
                <Form.Item label="头像" valuePropName="avatar">
                  <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                  >
                    {imageUrl ? (
                      <img
                        src={imageUrl}
                        alt="avatar"
                        style={{ width: '100%' }}
                      />
                    ) : (
                      uploadButton
                    )}
                  </Upload>
                </Form.Item>
              )}

              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </Form.Item>
            </Form>
          }
        </div>
      ),
    },
    {
      key: '2',
      label: `修改密码`,
      children: (
        <div>
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={async (val) => {
              console.log(val);
              const result = await postUpdatePassword({
                ...val,
                uid: JSON.parse(window.localStorage.getItem('token')),
              });
            }}
            // onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="旧密码"
              name="oldPassword"
              rules={[{ required: true, message: '请输入旧密码' }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item
              label="新密码"
              name="newPassword"
              rules={[{ required: true, message: '请输入新密码' }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </div>
      ),
    },
    {
      key: '3',
      label: `用户订单`,
      children: (
        <div>
          <Tabs defaultActiveKey="1" items={items2} />
        </div>
      ),
    },
    {
      key: '4',
      label: `发布的帖子`,
      children: (
        <div>
          <Search
            placeholder="请输入内容进行查询"
            style={{ width: '400px' }}
            allowClear
          />
          {postsList.map((x, idx) => {
            return (
              <Card key={idx} style={{ width: '100%', marginTop: '20px' }}>
                <div style={{ fontSize: '22px' }}>{x?.title}</div>
                <div>
                  <Space>
                    {x?.picture &&
                      JSON.parse(x?.picture).map((item, index) => {
                        return (
                          <Image
                            key={index}
                            width={150}
                            src={item}
                            placeholder={
                              <Image
                                preview={false}
                                src="https://th.bing.com/th?id=OIP.ynQBWO_RBkbw8rUhnp_1DQHaFj&w=288&h=216&c=8&rs=1&qlt=90&o=6&dpr=2&pid=3.1&rm=2"
                                width={150}
                              />
                            }
                          />
                        );
                      })}
                  </Space>
                  <div style={{ marginTop: '10px' }}>
                    <Space>
                      {/* <Button onClick={() => setIsModalOpen(true)}>修改</Button> */}
                      <Button onClick={async () => {
                        const result = await deletePost({
                          aid:x?.aid
                        })
                        if(result.state === 200){
                          message.success('删除成功')
                          setRefreshCount(refreshCount + 1)
                        }
                      }}>删除</Button>
                    </Space>
                  </div>
                </div>
              </Card>
            );
          })}

          <Modal
            title="编辑帖子"
            open={isModalOpen}
            // onOk={handleOk}
            onCancel={() => {
              setIsModalOpen(false);
            }}
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 17 }}
              layout="horizontal"
              style={{ maxWidth: 600 }}
            >
              <Form.Item label="标题">
                <Input />
              </Form.Item>
              <Form.Item label="图片" valuePropName="fileList">
                <Upload listType="picture-card">
                  <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>上传图片</div>
                  </div>
                </Upload>
              </Form.Item>
            </Form>
          </Modal>
        </div>
      ),
    },
    {
      key: '5',
      label: `发布的评论`,
      children: (
        <div>
          <Table dataSource={viewList} columns={columns3} />
        </div>
      ),
    },
  ];

  return (
    <PageContainer ghost>
      <Tabs
        tabPosition="left"
        defaultActiveKey="1"
        items={items}
        onChange={onChange}
      />
    </PageContainer>
  );
};

export default Mine;
